package com.example.testcamara;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Display;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.TextureView;
import android.view.WindowManager;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;


public class CameraController {
    private static String TAG = "CameraController";

    @Retention(RetentionPolicy.SOURCE)
    @IntDef({PHONE_HOME_BUTTON_BOTTOM, PHONE_HOME_BUTTON_TOP, PHONE_HOME_BUTTON_LEFT, PHONE_HOME_BUTTON_RIGHT})
    public @interface PhoneOrientation {
    }

    /**
     * 竖屏（home键在底部）
     */
    public static final int PHONE_HOME_BUTTON_BOTTOM = 0;
    /**
     * 反向竖屏（home键在顶部）
     */
    public static final int PHONE_HOME_BUTTON_TOP = 1;
    /**
     * 横屏（home键在左边）
     */
    public static final int PHONE_HOME_BUTTON_LEFT = 2;
    /**
     * 横屏（home键在右边）
     */
    public static final int PHONE_HOME_BUTTON_RIGHT = 3;

    private static Activity mActivity;
    private VideoRecordTextureView mTextureView;
    private Handler mBackgroundHandler;
    private String mBasePath;
    private String mFileName;
    private CameraDevice mCameraDevice;
    private Size mPreviewSize;
    private CaptureRequest.Builder mPreviewBuilder;
    private CaptureRequest.Builder mPreviewRequestBuilder;
    private MediaRecorder mMediaRecorder;
    private CameraCaptureSession mPreviewSession;
    private Integer mSensorOrientation;
    private CameraCaptureSession mCaptureSession;
    private String mCameraId = "" + CameraCharacteristics.LENS_FACING_BACK;
    private ImageReader mImageReader;
    private CaptureRequest mPreviewRequest;
    private static final int SENSOR_ORIENTATION_DEFAULT_DEGREES = 90;
    private static final int SENSOR_ORIENTATION_INVERSE_DEGREES = 270;
    private static final int STATE_PREVIEW = 0;
    private static final int STATE_WAITING_LOCK = 1;
    private static final int STATE_WAITING_PRECAPTURE = 2;
    private static final int STATE_WAITING_NON_PRECAPTURE = 3;
    private static final int STATE_PICTURE_TAKEN = 4;
    private int mState = STATE_PREVIEW;
    private final Semaphore mCameraOpenCloseLock = new Semaphore(1);
    private static final int MAX_PREVIEW_HEIGHT = 1280;
    private static final int MAX_PREVIEW_WIDTH = 720;
    private static final SparseIntArray ORIENTATION = new SparseIntArray();
    private boolean mFlashlightOn;
    private OrientationEventListener mRotationListener;
    @PhoneOrientation
    private int mPhoneOrientation = PHONE_HOME_BUTTON_BOTTOM;
    private OnPhoneOrientationChangeListener mOnPhoneOrientationChangeListener;
    private AtomicBoolean mIsRecording = new AtomicBoolean(false);

    static {
        ORIENTATION.append(Surface.ROTATION_0, 90);
        ORIENTATION.append(Surface.ROTATION_90, 0);
        ORIENTATION.append(Surface.ROTATION_180, 270);
        ORIENTATION.append(Surface.ROTATION_270, 180);
    }

    public CameraController(Activity activity) {
        mActivity = activity;
        mBasePath = activity.getExternalCacheDir().getPath();
    }

    public void initCamera(VideoRecordTextureView textureView) {
        this.mTextureView = (VideoRecordTextureView) textureView;
        startBackgroundThread();
        if (mTextureView.isAvailable()) {
            Log.e("EEDD", "mTextureView.isAvailable: " + mTextureView.getWidth() + " " + mTextureView.getHeight());
            openCamera(mTextureView.getWidth(), mTextureView.getHeight());
        } else {
            Log.e("EEDD", "mTextureView.isAvailable2: " + mTextureView.getWidth() + " " + mTextureView.getHeight());
            mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
        }
        mRotationListener = new OrientationEventListener(mActivity) {
            @Override
            public void onOrientationChanged(int orientation) {
                onOrientationRotate(orientation);
            }
        };
        mRotationListener.enable();
    }

    public void setOnPhoneOrientationChangeListener(OnPhoneOrientationChangeListener listener) {
        this.mOnPhoneOrientationChangeListener = listener;
    }

    /**
     * 屏幕旋转
     */
    @SuppressWarnings({"ConstantConditions", "AlibabaUndefineMagicConstant", "AlibabaAvoidComplexCondition"})
    private void onOrientationRotate(int orientation) {
        if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
            return;
        }
        // 根据设备方向进行相应的处理
        if (orientation >= 0 && orientation < 45 || orientation >= 315) {
            // 竖屏
            mPhoneOrientation = PHONE_HOME_BUTTON_BOTTOM;
        } else if (orientation >= 45 && orientation < 135) {
            // 左横屏
            mPhoneOrientation = PHONE_HOME_BUTTON_LEFT;
        } else if (orientation >= 135 && orientation < 225) {
            // 反向竖屏
            mPhoneOrientation = PHONE_HOME_BUTTON_TOP;
        } else if (orientation >= 225 && orientation < 315) {
            // 右横屏
            mPhoneOrientation = PHONE_HOME_BUTTON_RIGHT;
        }
        if (mOnPhoneOrientationChangeListener != null) {
            mOnPhoneOrientationChangeListener.onPhoneOrientationChanged(mPhoneOrientation);
        }
    }

    public void setFolderPath(String path) {
        this.mBasePath = path;
        File mFolder = new File(path);
        if (!mFolder.exists()) {
            if (!mFolder.mkdir()) {
                Log.d(TAG, "创建文件夹失败 " + path);
            }
        }
    }

    public void setFileName(String fileName) {
        mFileName = fileName;
    }

    public void takePicture() {
        lockFocus();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void startRecordingVideo() {
        if (mIsRecording.get()) {
            return;
        }
        if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
            return;
        }
        try {
            Log.e("ADDA", "111");
            closePreviewSession();
            Log.e("ADDA", "222");
            setUpMediaRecorder();
            Log.e("ADDA", "333");
//            mTextureView.setRotation(0);
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);

            List<Surface> surfaces = new ArrayList<>();
            Surface previewSurface = new Surface(texture);
            surfaces.add(previewSurface);
            mPreviewBuilder.addTarget(previewSurface);

            Surface recorderSurface = mMediaRecorder.getSurface();
            surfaces.add(recorderSurface);
            mPreviewBuilder.addTarget(recorderSurface);

            Log.e("ADDA", "444");
            mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    Log.e("ADDA", "555");
                    mPreviewSession = cameraCaptureSession;
                    updatePreview();
                    Log.e("ADDA", "666");
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mMediaRecorder.start();
                        }
                    });
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {

                }
            }, mBackgroundHandler);

            mIsRecording.set(true);
        } catch (Exception e) {
            Log.e("EEDD22", e.getMessage());
            Log.getStackTraceString(e);
        }
    }

    public void stopRecordingVideo() {
        closePreviewSession();

        try {
            mMediaRecorder.stop();
            mMediaRecorder.reset();
        } catch (Exception e) {
            Log.getStackTraceString(e);
        }

        startPreview();
        mIsRecording.set(false);
    }

    private void closePreviewSession() {
        if (null != mPreviewSession) {
            try {
                mPreviewSession.close();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    public void onPause() {
        stopRecordingVideo();
//        closeCamera();
//        closePreviewSession();
    }

    private void setUpMediaRecorder() throws IOException {
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mMediaRecorder.setOutputFile(getVideoFilePath());
        mMediaRecorder.setVideoEncodingBitRate(2000000); // 码流率 1M
        mMediaRecorder.setVideoFrameRate(25);
        Log.e("EEDD", "mPreviewSize: " + mPreviewSize.getWidth() + " " + mPreviewSize.getHeight());
        mMediaRecorder.setVideoSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        int rotation = getWindowDisplay(mActivity).getRotation();
//        mMediaRecorder.setOrientationHint(getOrientation(rotation));
        mMediaRecorder.setOrientationHint(getAdjustedOrientationForMediaRecord());
        mMediaRecorder.prepare();
        mMediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
            @Override
            public void onInfo(MediaRecorder mediaRecorder, int i, int i1) {
                Log.e(TAG, "录制完成");
            }
        });
    }

    private int getAdjustedOrientationForMediaRecord() {
        Camera.CameraInfo cameraInfo = getCameraInfo();
        int orientation = mActivity.getResources().getConfiguration().orientation;
        // Activity竖屏模式
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            // Home键在左右，即手机横置
            if (mPhoneOrientation == PHONE_HOME_BUTTON_RIGHT || mPhoneOrientation == PHONE_HOME_BUTTON_LEFT) {
                return 0;
            } else {
                // 前置摄像头
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    return 270;
                }
            }
        }
        // Activity横屏模式
        else {
            // Home键在上下，即手机纵置
            if (mPhoneOrientation == PHONE_HOME_BUTTON_BOTTOM || mPhoneOrientation == PHONE_HOME_BUTTON_TOP) {
                // 前置摄像头
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    return 270;
                } else {
                    return 90;
                }
            }
        }
//        // 前置摄像头 && 手机纵向时，录制的视频需要调整角度
//        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT
//                && (mPhoneOrientation == PHONE_HOME_BUTTON_BOTTOM || mPhoneOrientation == PHONE_HOME_BUTTON_TOP)) {
//            int orientation = mActivity.getResources().getConfiguration().orientation;
//            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
//                return 270;
//            } else {
//                return 180;
//            }
//        }
        int rotation = getWindowDisplay(mActivity).getRotation();
        return getOrientation(rotation);
    }

//    private int getAdjustedOrientationForMediaRecord() {
//        Camera.CameraInfo cameraInfo = getCameraInfo();
//
//        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
//            // 后置摄像头
//            return 90;
//        } else {
//            // 前置摄像头
//            if (mPhoneOrientation == PHONE_HOME_BUTTON_LEFT || mPhoneOrientation == PHONE_HOME_BUTTON_RIGHT) {
//                // 手机横置
//                return 90;
//            } else {
//                // 手机纵置
//                return 270;
//            }
//        }
//    }

    private String getVideoFilePath() {
        String path = mBasePath + "/videorecord/";
        File pathVideo = new File(path);
        if (!pathVideo.exists()) {
            if (!pathVideo.mkdir()) {
                return null;
            }
        }
        String fileName = (mFileName == null || mFileName.isEmpty()) ? getNowDate() : mFileName;
        return new File(path + fileName + ".mp4").getAbsolutePath();
    }

    private void updatePreview() {
        if (null == mCameraDevice) {
            return;
        }
        try {
            mPreviewBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
            mPreviewBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
            if (mFlashlightOn) {
                Log.e("EEDD", "updatePreview: 开启闪光灯");
                mPreviewBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
            } else {
                mPreviewBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
            }
            mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), null, mBackgroundHandler);
        } catch (Exception e) {
            Log.e("EEDD", "updatePreview: 开启闪光灯");
            Log.getStackTraceString(e);
        }
    }

    /**
     * 打开/关闭闪光灯
     *
     * @param enable true打开，false关闭
     */
    public void toggleFlashlight(boolean enable) {
        if (mIsRecording.get()) {
            return;
        }
        if (mFlashlightOn == enable) {
            return;
        }
//        if (mPreviewRequestBuilder != null) {
//            if (enable) {
//                mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
//            } else {
//                mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
//            }
//            if (mPreviewSession != null) {
//                try {
//                    mPreviewSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
            mFlashlightOn = !mFlashlightOn;
//        }
    }

    public void switchCamera() {
        if (mCameraId == null) {
            return;
        }

        // 关闭当前相机
        closeCamera();

        // 切换到另一个相机
        String newCameraId;
        Log.e("EEDD", "switchCamera: " + mCameraId);
        if (mCameraId.equals("" + CameraCharacteristics.LENS_FACING_FRONT)) {
            Log.e("EEDD", "switchCamera: " + mCameraId);
            newCameraId = "" + CameraCharacteristics.LENS_FACING_BACK;
        } else {
            Log.e("EEDD", "switchCamera: " + mCameraId);
            newCameraId = "" + CameraCharacteristics.LENS_FACING_FRONT;
        }

        // 打开新相机
        openCamera(newCameraId);
    }

    private void openCamera(String cameraId) {
        try {
            mCameraId = cameraId;
            CameraManager manager = (CameraManager) mActivity.getSystemService(Context.CAMERA_SERVICE);
            if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            manager.openCamera(cameraId, mStateCallback, mBackgroundHandler);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void closeCamera() {
        if (mCameraDevice != null) {
            mCameraDevice.close();
        }
        if (mCaptureSession != null) {
            mCaptureSession.close();
        }
    }

    private int getCameraOrientation() {
        Camera.CameraInfo info = getCameraInfo();
        int rotation = getWindowDisplay(mActivity).getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
            default:
                break;
        }
        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            // 获取当前设备的屏幕方向
//            if (isPhoneOrientationSameWithActivity()) {
//                result = (360 - result) % 360;
//            }
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        return result;
    }

    private Camera.CameraInfo getCameraInfo() {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(Integer.parseInt(mCameraId), info);
        return info;
    }

    private boolean isActivityPortrait() {
        int orientation = mActivity.getResources().getConfiguration().orientation;
        return orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    private boolean isActivityLandscape() {
        int orientation = mActivity.getResources().getConfiguration().orientation;
        return orientation == Configuration.ORIENTATION_LANDSCAPE;
    }

    /**
     * 手机的旋转方向和Activity方向是否一致（如手机本身是纵向Activity也是纵向）
     */
    private boolean isPhoneOrientationSameWithActivity() {
        int orientation = mActivity.getResources().getConfiguration().orientation;
        return orientation == Configuration.ORIENTATION_PORTRAIT &&
                (mPhoneOrientation == PHONE_HOME_BUTTON_BOTTOM || mPhoneOrientation == PHONE_HOME_BUTTON_TOP)
                || orientation == Configuration.ORIENTATION_LANDSCAPE &&
                (mPhoneOrientation == PHONE_HOME_BUTTON_LEFT || mPhoneOrientation == PHONE_HOME_BUTTON_RIGHT);
    }

    /**
     * 手机竖着（指手机本身，不是Activity的横屏竖屏）
     */
    private boolean isPhoneOrientationPortrait() {
        return mPhoneOrientation == PHONE_HOME_BUTTON_BOTTOM || mPhoneOrientation == PHONE_HOME_BUTTON_TOP;
    }

    /**
     * 手机横着（指手机本身，不是Activity的横屏竖屏）
     */
    private boolean isPhoneOrientationLandscape() {
        return mPhoneOrientation == PHONE_HOME_BUTTON_LEFT || mPhoneOrientation == PHONE_HOME_BUTTON_RIGHT;
    }

    private void lockFocus() {
        try {
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                    CameraMetadata.CONTROL_AF_TRIGGER_START);
            mState = STATE_WAITING_LOCK;
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
        } catch (Exception e) {
            Log.getStackTraceString(e);
        }
    }

    private File getPicFile() {
        String path = mBasePath + "/pic/";
        File pathPic = new File(path);
        if (!pathPic.exists()) {
            if (!pathPic.mkdir()) {
                return null;
            }
        }
        String fileName = (mFileName == null || mFileName.isEmpty()) ? getNowDate() : mFileName;
        return new File(path + fileName + ".jpg");
    }

    private String getNowDate() {
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(new Date());
    }

    private final TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            openCamera(width, height);
        }

        @Override
        public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surfaceTexture) {
            Log.e("EEDD", "onSurfaceTextureDestroyed");
            closePreviewSession();
            return true;
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
            // 在SurfaceTexture尺寸发生变化时调整相机预览尺寸
            configureTransform(width, height);
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {
        }
    };

    private void startBackgroundThread() {
        HandlerThread mBackgroundThread = new HandlerThread("CameraBackground");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }

    private void openCamera(int width, int height) {
        Log.e("EEDD", "openCamera: " + width + " " + height);
        setUpCameraOutputs(width, height);
        CameraManager manager = (CameraManager) mActivity.getSystemService(Context.CAMERA_SERVICE);
        try {
            if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("Time out waiting to lock camera opening.");
            }
            if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
        } catch (CameraAccessException e) {
            Log.e(TAG, Log.getStackTraceString(e));
        } catch (InterruptedException e) {
            Log.e(TAG, "********** InterruptedException" + Log.getStackTraceString(e));
            throw new RuntimeException("Interrupted while trying to lock camera opening", e);
        } catch (RuntimeException e) {
            Log.e(TAG, "********** RuntimeException" + Log.getStackTraceString(e));
        }
    }

    private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {
            mCameraOpenCloseLock.release();
            mCameraDevice = cameraDevice;
            Log.e("EEDD", "onOpened");
            startPreview();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            mCameraOpenCloseLock.release();
            mCameraDevice.close();
            mCameraDevice = null;
        }

        @Override
        public void onError(@NonNull CameraDevice cameraDevice, int error) {
            mCameraOpenCloseLock.release();
            if (mCameraDevice != null) {
                mCameraDevice.close();
            }
            mCameraDevice = null;
            mActivity.finish();
        }
    };

    /**
     * 设置相机显示方向的详细解读
     **/
    public static void setCameraDisplayOrientation(int cameraId, Camera camera) {
        // 1.获取屏幕切换角度值。
        int rotation = mActivity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }
        // 2.获取摄像头方向。
        Camera.CameraInfo info =
                new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId, info);
        // 3.设置相机显示方向。
        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }


    private void startPreview() {
        try {
//            setCameraDisplayOrientation();
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            Surface surface = new Surface(texture);
            mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            mPreviewRequestBuilder.addTarget(surface);
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
            mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureResult.FLASH_MODE_OFF);
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

            mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                    new CameraCaptureSession.StateCallback() {
                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                            if (null == mCameraDevice) {
                                return;
                            }
                            mCaptureSession = cameraCaptureSession;
                            mPreviewRequest = mPreviewRequestBuilder.build();
                            try {
                                mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler);
                            } catch (Exception e) {
                                Log.e(TAG, Log.getStackTraceString(e));
                            }
                        }

                        @Override
                        public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                        }
                    }, null);
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    private CameraCaptureSession.CaptureCallback mCaptureCallback = new CameraCaptureSession.CaptureCallback() {
        private void process(CaptureResult result) {
            switch (mState) {
                case STATE_PREVIEW: {
                    break;
                }
                case STATE_WAITING_LOCK: {
                    Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
                    if (afState == null) {
                        captureStillPicture();
                    } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState
                            || CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) {
                        Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                        if (null == aeState || aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
                            mState = STATE_PICTURE_TAKEN;
                            captureStillPicture();
                        } else {
                            runPrecaptureSequence();
                        }
                    }
                    break;
                }
                case STATE_WAITING_PRECAPTURE: {
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null
                            || aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE
                            || aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
                        mState = STATE_WAITING_NON_PRECAPTURE;
                    }
                    break;
                }
                case STATE_WAITING_NON_PRECAPTURE: {
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
                        mState = STATE_PICTURE_TAKEN;
                        captureStillPicture();
                    }
                    break;
                }
            }
        }

        @Override
        public void onCaptureProgressed(@NonNull CameraCaptureSession session,
                                        @NonNull CaptureRequest request,
                                        @NonNull CaptureResult partialResult) {
            process(partialResult);
        }

        @Override
        public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                       @NonNull CaptureRequest request,
                                       @NonNull TotalCaptureResult result) {
//            Log.e(TAG, "onCaptureCompleted");
            process(result);
        }
    };

    private void captureStillPicture() {
        try {
            if (null == mCameraDevice) {
                return;
            }
            final CaptureRequest.Builder captureBuilder =
                    mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureBuilder.addTarget(mImageReader.getSurface());
            captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
            captureBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
            captureBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
            captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            int rotation = getWindowDisplay(mActivity).getRotation();
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));
            CameraCaptureSession.CaptureCallback captureCallback =
                    new CameraCaptureSession.CaptureCallback() {
                        @Override
                        public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                                       @NonNull CaptureRequest request,
                                                       @NonNull TotalCaptureResult result) {
                            unlockFocus();
                        }
                    };
            mCaptureSession.stopRepeating();
            mCaptureSession.capture(captureBuilder.build(), captureCallback, null);
        } catch (CameraAccessException e) {
            Log.getStackTraceString(e);
        }
    }

    private Display getWindowDisplay(Context context) {
        return ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    }

    private int getOrientation(int rotation) {
        return (ORIENTATION.get(rotation) + mSensorOrientation + 270) % 360;
    }

    private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
        boolean mFlashSupported = true;
        if (mFlashSupported) {
            requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
                    CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
        }
    }

    private void unlockFocus() {
        try {
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                    CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
            setAutoFlash(mPreviewRequestBuilder);
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler);
            mState = STATE_PREVIEW;
            mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler);
        } catch (CameraAccessException e) {
            Log.getStackTraceString(e);
        }
    }

    private void runPrecaptureSequence() {
        try {
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
                    CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL);
            mState = STATE_WAITING_PRECAPTURE;
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
        } catch (CameraAccessException e) {
            Log.getStackTraceString(e);
        }
    }

    private ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {
        @Override
        public void onImageAvailable(ImageReader imageReader) {
            mBackgroundHandler.post(new ImageSaver(imageReader.acquireNextImage(), getPicFile()));
        }
    };

    private void setUpCameraOutputs(int width, int height) {
        CameraManager manger = (CameraManager) mActivity.getSystemService(Context.CAMERA_SERVICE);
        try {
            Log.d("EEDD", "getCameraIdList: " + manger.getCameraIdList());
            for (String cameraId : manger.getCameraIdList()) {
                CameraCharacteristics characteristics = manger.getCameraCharacteristics(cameraId);
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                    Log.d("EEDD", "facing CameraCharacteristics.LENS_FACING_FRONT ");
                    continue;
                }
                StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                if (map == null) {
                    Log.d("EEDD", "null == map");
                    return;
                }
                Size[] canmeraSizes = map.getOutputSizes(ImageFormat.JPEG);
                Point displaySize = new Point();
                getWindowDisplay(mActivity).getSize(displaySize);
                mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
                Arrays.sort(canmeraSizes, new CompareSizesByArea());
                boolean swap = (90 == mSensorOrientation || 270 == mSensorOrientation);
                Log.d("EEDD", "canmeraSizes: " + canmeraSizes.length);
                for (int i = canmeraSizes.length - 1; i >= 0; i--) {
                    int w = 0;
                    int h = 0;
                    if (swap) {
                        w = canmeraSizes[i].getHeight();
                        h = canmeraSizes[i].getWidth();
                    } else {
                        w = canmeraSizes[i].getWidth();
                        h = canmeraSizes[i].getHeight();
                    }
                    Log.d("EEDD", "W " + w + " H " + h);
                    if (MAX_PREVIEW_WIDTH >= w && MAX_PREVIEW_HEIGHT >= h) {
                        int surfaceW;
                        int surfaceH;
                        if (swap) {
                            surfaceW = h;
                            surfaceH = w;
                        } else {
                            surfaceW = w;
                            surfaceH = h;
                        }
                        Log.e("EEDD", "W " + w + " H " + h);
                        Log.e("EEDD", "surfaceW " + surfaceW + " surfaceH " + surfaceH);
                        mPreviewSize = new Size(surfaceW, surfaceH);
                        // 获取当前设备的屏幕方向
                        int orientation = mActivity.getResources().getConfiguration().orientation;
                        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                            // 当前为竖屏
                            mTextureView.setAspectRatio(displaySize.x, displaySize.x * h / w);
                        } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                            // 当前为横屏
                            mTextureView.setAspectRatio(displaySize.x * h / w, displaySize.x);
                        }
                        mImageReader = ImageReader.newInstance(surfaceW, surfaceH, ImageFormat.JPEG, 3);
                        mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
                        mMediaRecorder = new MediaRecorder();
                        mCameraId = cameraId;
                        return;
                    }
                }
            }
        } catch (Exception e) {
            Log.getStackTraceString(e);
        }
    }

    static class CompareSizesByArea implements Comparator<Size> {
        @Override
        public int compare(Size lhs, Size rhs) {
            return Long.signum((long) lhs.getWidth() * lhs.getHeight() - (long) rhs.getWidth() * rhs.getHeight());
        }
    }

    private static Size chooseOptimalSize(Size[] choices, int textureViewWidth, int textureViewHeight,
                                          int maxWidth, int maxHeight, Size aspectRatio) {
        List<Size> bigEnough = new ArrayList<>();
        List<Size> notBigEnough = new ArrayList<>();
        int w = aspectRatio.getWidth();
        int h = aspectRatio.getHeight();
        for (Size option : choices) {
            if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight
                    && option.getHeight() == option.getWidth() * h / w) {
                if (option.getWidth() >= textureViewWidth
                        && option.getHeight() >= textureViewHeight) {
                    bigEnough.add(option);
                } else {
                    notBigEnough.add(option);
                }
            }
        }
        if (bigEnough.size() > 0) {
            return Collections.min(bigEnough, new CompareSizesByArea());

        } else if (notBigEnough.size() > 0) {
            return Collections.max(notBigEnough, new CompareSizesByArea());
        } else {
            return choices[0];
        }
    }

    private void configureTransform(int viewWidth, int viewHeight) {
        if (null == mTextureView || null == mPreviewSize) {
            return;
        }

        int rotation = getWindowDisplay(mActivity).getRotation();
        Matrix matrix = new Matrix();
        RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
        RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
        float centerX = viewRect.centerX();
        float centerY = viewRect.centerY();

        if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
            bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
            matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);

            float scale = Math.max((float) viewHeight / mPreviewSize.getHeight(),
                    (float) viewWidth / mPreviewSize.getWidth());
            matrix.postScale(scale, scale, centerX, centerY);
            matrix.postRotate(90 * (rotation - 2), centerX, centerY);
        } else if (Surface.ROTATION_180 == rotation) {
            matrix.postRotate(180, centerX, centerY);
        }
        mTextureView.setTransform(matrix);
    }

    private static class ImageSaver implements Runnable {
        private final Image mImage;
        private final File mFile;

        public ImageSaver(Image image, File file) {
            mImage = image;
            mFile = file;
        }

        @Override
        public void run() {
            ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);

            FileOutputStream output = null;
            try {
                output = new FileOutputStream(mFile);
                output.write(bytes);
            } catch (IOException e) {
                Log.getStackTraceString(e);
            } finally {
                mImage.close();
                if (null != output) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        Log.getStackTraceString(e);
                    }
                }
            }
        }
    }

    interface OnPhoneOrientationChangeListener {
        void onPhoneOrientationChanged(@PhoneOrientation int orientation);
    }
}
